"""
Array Backed Grid
栅格绘画（原始画法）

Show how to use a two-dimensional list/array to back the display of a
grid on-screen.
展示如何使用二维数组在屏幕北京展示栅格

Note: Regular drawing commands are slow. Particularly when drawing a lot of
items, like the rectangles in this example.
使用通常的画矩形的方法，速度比较慢

For faster drawing, create the shapes and then draw them as a batch.
See array_backed_grid_buffered.py
如果要快速绘画，使用批量绘画

If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.array_backed_grid
"""
import arcade

# Set how many rows and columns we will have
# 行的数量和列的数量
ROW_COUNT = 15
COLUMN_COUNT = 15

# This sets the WIDTH and HEIGHT of each grid location
# 每个栅格的宽度和高度
WIDTH = 30
HEIGHT = 30

# This sets the margin between each cell
# and on the edges of the screen.
# 外边宽处理
MARGIN = 5

# Do the math to figure out our screen dimensions
# 窗口的宽度和高度（根据以上信息自动计算）
# 以宽度为例，总宽度=cell_width*column_count+margin*(column_count+1)
WINDOW_WIDTH = (WIDTH + MARGIN) * COLUMN_COUNT + MARGIN
WINDOW_HEIGHT = (HEIGHT + MARGIN) * ROW_COUNT + MARGIN
WINDOW_TITLE = "Array Backed Grid Example"


class GameView(arcade.View):
    """
    Main application class.
    """

    def __init__(self):
        """
        Set up the application.
        """
        # 父类View必执行__init__方法
        super().__init__()

        # Create a 2 dimensional array. A two-dimensional
        # array is simply a list of lists.
        # 构建矩阵数据
        # 等同于：self.grid=[[0]*COLUMN_COUNT for _ in range(ROW_COUNT)]
        self.grid = []
        for row in range(ROW_COUNT):
            # Add an empty array that will hold each cell
            # in this row
            self.grid.append([])
            for column in range(COLUMN_COUNT):
                self.grid[row].append(0)  # Append a cell

        # 设置背景颜色
        self.background_color = arcade.color.BLACK

    def on_draw(self):
        """
        Render the screen.
        """

        # This command has to happen before we start drawing
        # 固定调用clear
        self.clear()

        # Draw the grid
        for row in range(ROW_COUNT):
            for column in range(COLUMN_COUNT):
                # Figure out what color to draw the box
                # 使用1标识用鼠标点击过的位置
                if self.grid[row][column] == 1:
                    color = arcade.color.GREEN
                else:
                    color = arcade.color.WHITE

                # Do the math to figure out where the box is
                # 计算坐标，即单元格中心的xy坐标
                # 注：这里的row实际是从底部向上数的
                x = (MARGIN + WIDTH) * column + MARGIN + WIDTH // 2
                y = (MARGIN + HEIGHT) * row + MARGIN + HEIGHT // 2

                # Draw the box
                # 根据中心和宽高，画矩形
                arcade.draw_rect_filled(arcade.rect.XYWH(x, y, WIDTH, HEIGHT), color)

    def on_mouse_press(self, x, y, button, modifiers):
        """
        Called when the user presses a mouse button.
        """

        # Change the x/y screen coordinates to grid coordinates
        # 根据xy坐标计算行列，同时用去尾法计算真实的值（一种较快捷的技巧）
        column = int(x // (WIDTH + MARGIN))
        row = int(y // (HEIGHT + MARGIN))

        print(f"Click coordinates: ({x}, {y}). Grid coordinates: ({row}, {column})")

        # Make sure we are on-grid. It is possible to click in the upper right
        # corner in the margin and go to a grid location that doesn't exist
        # 此处判断，是考虑点击到右侧或顶部边界的情况
        if row < ROW_COUNT and column < COLUMN_COUNT:

            # Flip the location between 1 and 0.
            # 点击之后变更active状态
            if self.grid[row][column] == 0:
                self.grid[row][column] = 1
            else:
                self.grid[row][column] = 0


def main():
    """ Main function """
    # Create a window class. This is what actually shows up on screen
    window = arcade.Window(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE)

    # Create the GameView
    game = GameView()

    # Show GameView on screen
    window.show_view(game)

    # Start the arcade game loop
    arcade.run()


if __name__ == "__main__":
    main()